package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// RESTful标准控制器
//@RestController = @Controller + @ResponseBody
//子容器中bean
@RestController
@RequestMapping("/books")
public class BookController {
    //从父容器中获取bean
    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {

//        return bookService.save(book);
        //如果返回true,表示保存成功
        boolean flag = bookService.save(book);
//        Result result;
//        if(flag){
//            result = new Result(Code.SAVE_OK,flag,"保存成功");
//        }else{
//            result = new Result(Code.SAVE_ERR,flag,"保存失败");
//        }

        Result result = flag ? new Result(Code.SAVE_OK,flag,"保存成功") :  new Result(Code.SAVE_ERR,flag,"保存失败");
        return result;
    }

    @PutMapping
    public Result update(@RequestBody Book book) {
//        return bookService.update(book);
        boolean flag = bookService.update(book);
        Result result = flag ? new Result(Code.UPDATE_OK,flag,"修改成功") :  new Result(Code.UPDATE_ERR,flag,"修改失败");
        return result;
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {

//        return bookService.delete(id);
        boolean flag = bookService.delete(id);
        Result result = flag ? new Result(Code.DELETE_OK,flag,"删除成功") :  new Result(Code.DELETE_ERR,flag,"删除失败");
        return result;
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        if(id <= 0){
            throw new BusinessException(Code.BUSINESS_ERR,"id不能小于等于0");
        }
        if(id == 1){
            //id=1假装会出现异常系统
            throw new SystemException(Code.SYSTEM_ERR,"当前服务器繁忙,请稍后重试");
        }

//        return bookService.getById(id);
//        int i = 1/0; // 算术异常: ArithmeticException
        Book book = bookService.getById(id);
        Result result = book!=null?new Result(Code.GET_OK,book,"查询单个成功")
                :  new Result(Code.GET_ERR,null,"查询单个失败");
        return result;
    }

    @GetMapping
    public Result getAll() {
//        String str = null;
//        str.length(); // 空指针异常:  NullPointerException
//        return bookService.getAll();
        List<Book> list = bookService.getAll();
        Result result = list !=null && list.size() > 0?new Result(Code.GET_OK,list,"查询全部成功")
                :  new Result(Code.GET_ERR,null,"查询全部失败");
        return result;
    }
}
